package com.gmail.skwong.speedplayer;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

/**
 * This class is responsible for listening for magnetic spikes. An interface is
 * provided to choose what happens during a spike.
 * 
 * @author Stephen
 * 
 */
public class MagneticFieldListener implements SensorEventListener {

	private OnMagneticSpikeListener mMagneticSpikeListener;
	private long lastUpdate;
	private Context mContext;

	public interface OnMagneticSpikeListener {
		void onSpike();
	}

	public MagneticFieldListener(Context context) {
		lastUpdate = System.currentTimeMillis();
		mContext = context;
	}

	public void setOnMagneticSpikeListener(OnMagneticSpikeListener listener) {
		mMagneticSpikeListener = listener;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		float[] values = event.values;
		float x = values[0];
		float y = values[1];
		float z = values[2];

		float magnitude = (float) Math.sqrt(x * x + y * y + z * z);
		long actualTime = System.currentTimeMillis();
		if (magnitude > mContext.getResources().getInteger(
				R.integer.magnetic_field_threshold)) {
			if (actualTime - lastUpdate < mContext.getResources().getInteger(
					R.integer.magnetic_field_min_wait_time)) {
				return;
			}
			lastUpdate = actualTime;
			mMagneticSpikeListener.onSpike();
		}

	}
}